package cn.lysoy.demo.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
class RestUtil {

    public static void main(String[] args) {
//        System.out.println(verifyUrl(" "));
//        System.out.println(verifyUrl("http://123"));
//        System.out.println(verifyUrl("https://123"));
//        System.out.println(verifyUrl(""));
//        System.out.println(verifyUrl(null));
        System.out.println(isAlive("127.0.0.1", 1000));
        System.out.println(isAlive("", 1000));
        System.out.println(isAlive(null, 1000));
        System.out.println(isAlive("1", 1000));
        System.out.println(isAlive("127.0.0.2", 1000));
    }

    public static boolean verifyUrl(String url){
        if (null == url || url.length() == 0) {
            return false;
        }
        // URL验证规则
        String regEx ="[a-zA-z]+://[^\\s]*";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        // 忽略大小写的写法
        // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(url);
        // 字符串是否与正则表达式相匹配
        boolean rs = matcher.matches();
        return rs;
    }

    public static boolean isAlive(String host, int timeout){
        if (null == host || host.length() == 0) {
            return false;
        }
        InetAddress byName;
        try {
            byName = InetAddress.getByName(host);
        }catch (UnknownHostException e) {
            log.info(e.getMessage());
            return false;
        }if (byName == null) {
            return false;
        }else {
            try {
                boolean reachable = byName.isReachable(timeout);
                return reachable;
            }catch (IOException e) {
                log.info(e.getMessage());
                return false;
            }
        }
    }
}